package com.general.framework.web.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.general.framework.core.exception.Ex;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author leejean
 * @ClassName: IpAddressUtil
 * @Description: IP地址工具类
 * @date 2019年10月29 18:30:50
 */
@Slf4j
public class IpAddressUtil {

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 参考文章： http://developer.51cto.com/art/201111/305181.htm
     * <p>
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     * <p>
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     * <p>
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(final HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 把字符串IP转换成Integer
     *
     * @param ipStr 字符串IP
     * @return IP对应的long值
     */
    public static Integer ip2Int(final String ipStr) {
        final String[] ip = ipStr.split("\\.");
        return (Integer.valueOf(ip[0]) << 24) + (Integer.valueOf(ip[1]) << 16) + (Integer.valueOf(ip[2]) << 8)
                + Integer.valueOf(ip[3]);
    }

    /**
     * 把IP的Integer值转换成字符串
     *
     * @param ipInt IP的long值
     * @return long值对应的字符串
     */
    public static String int2Ip(final Integer ipInt) {
        final StringBuilder ip = new StringBuilder();
        ip.append(ipInt >>> 24).append(".");
        ip.append((ipInt >>> 16) & 0xFF).append(".");
        ip.append((ipInt >>> 8) & 0xFF).append(".");
        ip.append(ipInt & 0xFF);
        return ip.toString();
    }

    public static Integer getIntIpAddress(final HttpServletRequest request) {
        return ip2Int(getIpAddress(request));
    }

    /**
     * 获取IP
     *
     * @param interfaceName 网卡名称
     * @return
     */
    public static String getIp(String interfaceName) {
        List<String> ipList = getHostAddress(interfaceName);
        final String ip = ipList.isEmpty() ? null : ipList.get(0);
        return ip;
    }

    /**
     * 获取已激活网卡的IP地址
     *
     * @param interfaceName 可指定网卡名称,null则获取全部
     * @return List<String>
     */
    private static List<String> getHostAddress(String interfaceName) {
        Enumeration<NetworkInterface> interfaces;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            log.error("获取网卡信息失败", e);
            throw Ex.systemError("获取网卡信息失败");
        }
        List<String> ipList = new ArrayList<>(5);
        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();
            Enumeration<InetAddress> allAddress = ni.getInetAddresses();
            while (allAddress.hasMoreElements()) {
                InetAddress address = allAddress.nextElement();
                if (address.isLoopbackAddress()) {
                    // skip the loopback addr
                    continue;
                }
                if (address instanceof Inet6Address) {
                    // skip the IPv6 addr
                    continue;
                }
                String hostAddress = address.getHostAddress();
                if (null == interfaceName) {
                    ipList.add(hostAddress);
                } else if (interfaceName.equals(ni.getDisplayName())) {
                    ipList.add(hostAddress);
                }
            }
        }
        return ipList;
    }

    public static String getAddress(String ip) {
        if (Strings.isEmpty(ip)) {
            return "unknown";
        }
        if ("127.0.0.1".equals(ip)) {
            return "内网IP";
        }
        if (ip.contains(",")) {
            List<String> addressList = new ArrayList<>();
            Lists.asList(ip.split(",")).forEach(oneIp->addressList.add(getOneIpAddress(oneIp)));
            return Strings.join(addressList, ",");
        }
        return getOneIpAddress(ip);
    }

    private static String getOneIpAddress(String ip) {
        if ("127.0.0.1".equals(ip)) {
            return "内网IP";
        }
        String url = Strings.format("http://opendata.baidu.com/api.php?query={}&co=&resource_id=6006&oe=utf8", ip);
        try {
            String result = HttpUtil.sendGet(url, null,"GBK");
            if (Strings.isNotEmpty(result)) {
                final JSONObject resultJson = Jsons.parseObject(result);
                final JSONArray jsonArray = resultJson.getJSONArray("data");
                if (jsonArray.size() > 0) {
                    final JSONObject jsonObject = jsonArray.getJSONObject(0);
                    return jsonObject.getString("location");
                }
            }
        } catch (Exception e) {
            log.error("getAddress error", e);
        }
        return "unknown";
    }

}
